import os
import datetime
import hashlib
from google.appengine.api import urlfetch
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.db import BadKeyError
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from models import Shelf, ShelfItem, ShelfItemMeta
from tmdb import TMDb

class ShelfViewPage(webapp.RequestHandler):
    
    def get(self, shelf_id):

        # Check to see if the shelf exists
        try:
            shelf = Shelf.get(shelf_id)
            if shelf.owner != users.get_current_user() and shelf.public != False:
                self.redirect('/')
            values = {'shelf': shelf}
        except BadKeyError:
            values = {'shelf': {}}
        
        self.response.out.write(template.render('templates/header.html', {}))
        self.response.out.write(template.render('templates/shelf/view.html', values))
        self.response.out.write(template.render('templates/footer.html', {}))

class ShelfListPage(webapp.RequestHandler):
    
    def get(self):
       
        user = users.get_current_user()
        gravatar = 'http://www.gravatar.com/avatar/%s' % hashlib.md5(user.email()).hexdigest()
        shelves = Shelf.gql('WHERE owner = USER(\'%s\')' % user.email())
        values = {'shelves':shelves, 
                  'shelf_count': shelves.count(),
                  'username': user.nickname(),
                  'gravatar': gravatar}
        
        self.response.out.write(template.render('templates/header.html', {}))
        self.response.out.write(template.render('templates/shelf/list.html', values))
        self.response.out.write(template.render('templates/footer.html', {}))

class ShelfListOrderedPage(webapp.RequestHandler):        
        
    def get(self, order_by_attr):
       
        user = users.get_current_user()
        gravatar = 'http://www.gravatar.com/avatar/%s' % hashlib.md5(user.email()).hexdigest()
        if order_by_attr:
            if order_by_attr == 'date':
                shelves = Shelf.gql('WHERE owner = USER(\'%s\') ORDER BY created' % user.email())
            if order_by_attr == 'name':
                shelves = Shelf.gql('WHERE owner = USER(\'%s\') ORDER BY name' % user.email())  
        else:
            shelves = Shelf.gql('WHERE owner = USER(\'%s\')' % user.email())
        values = {'shelves':shelves,
                  'shelf_count': shelves.count(),
                  'username': user.nickname(),
                  'gravatar': gravatar}
        
        self.response.out.write(template.render('templates/header.html', {}))
        self.response.out.write(template.render('templates/shelf/list.html', values))
        self.response.out.write(template.render('templates/footer.html', {}))

class ShelfAddPage(webapp.RequestHandler):
    
    def post(self):
        
        shelf = Shelf(name=self.request.get('name'), owner=users.get_current_user())
        shelf.put()
        self.redirect('/shelf/list')
    
    def get(self):
        
        user = users.get_current_user()
        
        self.response.out.write(template.render('templates/header.html', {}))
        self.response.out.write(template.render('templates/shelf/add.html', {}))
        self.response.out.write(template.render('templates/footer.html', {}))

class ShelfViewItemPage(webapp.RequestHandler):

    def get(self, shelf_id, item_id):
        
        shelf = Shelf.get(shelf_id)
        if shelf.owner != users.get_current_user() and shelf.public != False:
            self.redirect('/')
        item = ShelfItem.get(item_id)
        meta = item.meta
        movie_id = ""
        for meta_item in meta:
            if meta_item.name == "Movie ID":
                movie_id = meta_item.value
        values = {'shelf': shelf,
                  'item': item,
                  'meta_count': item.meta.count(),
                  'shelf_id': shelf_id,
                  'item_id': item_id,
                  'movie_id': movie_id}
        
        self.response.out.write(template.render('templates/header.html', {}))
        self.response.out.write(template.render('templates/shelf/item/view.html', values))
        self.response.out.write(template.render('templates/footer.html', {}))


class ShelfAddItemPage(webapp.RequestHandler):
    
    def post(self, shelf_id):
        if self.request.get('movie'):
            self.redirect('/shelf/' + shelf_id + '/add/movie/' + self.request.get('movie'))
        else:
            curr_shelf = Shelf.get(shelf_id)
            shelf_item = ShelfItem(name=self.request.get('name'), shelf=curr_shelf)
            shelf_item.put()
            self.redirect('/shelf/'+shelf_id)
    
    def get(self, shelf_id):
        
        values = {'shelf': Shelf.get(shelf_id),
                  'user': users.get_current_user()}
        
        self.response.out.write(template.render('templates/header.html', {}))
        self.response.out.write(template.render('templates/shelf/item/add.html', values))
        self.response.out.write(template.render('templates/footer.html', {}))

class ShelfDeleteItemPage(webapp.RequestHandler):
    
    def post(self, shelf_id, item_id):
        
        if item_id != self.request.get('item_id'):
            self.redirect('/shelf/%s' % shelf_id)
        else:
            
            item = ShelfItem.get(item_id)
            
            # delete the item
            for data in item.meta:
                data.delete()
            item.delete()
            
            # return to the shelf page
            self.redirect('/shelf/%s' % shelf_id)
        
    def get(self, shelf_id, item_id):
        
        values = {'shelf': Shelf.get(shelf_id),
                  'item': ShelfItem.get(item_id),
                  'user': users.get_current_user()}
        
        self.response.out.write(template.render('templates/header.html', {}))
        self.response.out.write(template.render('templates/shelf/item/delete.html', values))
        self.response.out.write(template.render('templates/footer.html', {}))

class ShelfEditItemPage(webapp.RequestHandler):
    
    def post(self, shelf_id, item_id):
        
        item = ShelfItem.get(item_id)
        item.name = self.request.get('name')
        item.put()
        
        self.redirect('/shelf/%s' % shelf_id)
        
    def get(self, shelf_id, item_id):
        
        values = {'shelf': Shelf.get(shelf_id),
                  'item': ShelfItem.get(item_id),
                  'user': users.get_current_user()}
        
        self.response.out.write(template.render('templates/header.html', {}))
        self.response.out.write(template.render('templates/shelf/item/edit.html', values))
        self.response.out.write(template.render('templates/footer.html', {}))



class ShelfAddMoviePage(webapp.RequestHandler):
    
    def post(self, shelf_id, movie):
        curr_shelf = Shelf.get(shelf_id)
        shelf_item = ShelfItem(name=self.request.get('movie_title'), shelf=curr_shelf)
        shelf_item.put()
        movie_id = self.request.get('movie_id')
        shelf_item_meta = ShelfItemMeta(shelf_item=shelf_item, name='Movie ID' , type='text' , value=movie_id)
        shelf_item_meta.put()
        shelf_item_meta = ShelfItemMeta(shelf_item=shelf_item, name='imdb_id', type='url', value=self.request.get('imdb_id'))
        shelf_item_id = shelf_item.key()
        self.redirect('/shelf/' + shelf_id + '/add/movie/meta/' + str(shelf_item_id) + '/' + movie_id)

        
    def get(self, shelf_id, movie):
        tmdbapi = TMDb('58bdd901955465b24e37631dd9f68ced')
        results = tmdbapi.search(movie)
        values = {'results':results}
        
        self.response.out.write(template.render('templates/header.html', {}))
        self.response.out.write(template.render('templates/shelf/item/addmoviesearchresults.html', values))
        self.response.out.write(template.render('templates/footer.html', {}))

class ShelfItemAddMetaPage(webapp.RequestHandler):
    
    def post(self, shelf_id, item_id):
        
        item = ShelfItem.get(item_id)
        meta = ShelfItemMeta(name = self.request.get('name'),
                             value = self.request.get('value'),
                             type = self.request.get('type'),
                             shelf_item = item)
        meta.put()
        
        self.redirect('/shelf/%s/%s' % (shelf_id, item_id))
    
    def get(self, shelf_id, item_id):

        values = {'shelf': Shelf.get(shelf_id),
                  'item': ShelfItem.get(item_id),
                  'user': users.get_current_user()}
        
        self.response.out.write(template.render('templates/header.html', {}))
        self.response.out.write(template.render('templates/shelf/item/meta/add.html', values))
        self.response.out.write(template.render('templates/footer.html', {}))
        
class ShelfItemDeleteMetaPage(webapp.RequestHandler):
    
    def post(self, meta_id):
        
        meta = ShelfItemMeta.get(meta_id)
        item = meta.shelf_item
        shelf = item.shelf
    
        meta.delete()
        
        self.redirect('/shelf/%s/%s' % (str(shelf.key()), str(item.key())))
    
    def get(self, meta_id):

        meta = ShelfItemMeta.get(meta_id)
        item = meta.shelf_item
        shelf = meta.shelf_item.shelf

        values = {'shelf': shelf,
                  'item': item,
                  'meta': meta,
                  'user': users.get_current_user()}
        
        self.response.out.write(template.render('templates/header.html', {}))
        self.response.out.write(template.render('templates/shelf/item/meta/delete.html', values))
        self.response.out.write(template.render('templates/footer.html', {}))

class ShelfItemEditMetaPage(webapp.RequestHandler):
    
    def post(self, meta_id):
        
        meta = ShelfItemMeta.get(meta_id)
        item = meta.shelf_item
        shelf = item.shelf
        
        meta.name = self.request.get('name')
        meta.value = self.request.get('value')
        meta.type = self.request.get('type')
        meta.put()
        
        self.redirect('/shelf/%s/%s' % (str(shelf.key()), str(item.key())))
    
    def get(self, meta_id):

        meta = ShelfItemMeta.get(meta_id)
        item = meta.shelf_item
        shelf = meta.shelf_item.shelf

        values = {'shelf': shelf,
                  'item': item,
                  'meta': meta,
                  'user': users.get_current_user(),
                  'type_text': 'selected' if meta.type == 'text' else '',
                  'type_url': 'selected' if meta.type == 'url' else '',
                  'type_image': 'selected' if meta.type == 'image' else ''}
        
        self.response.out.write(template.render('templates/header.html', {}))
        self.response.out.write(template.render('templates/shelf/item/meta/edit.html', values))
        self.response.out.write(template.render('templates/footer.html', {}))

class ShelfItemAddMovieMeta(webapp.RequestHandler):
    
    def post(self, shelf_id, shelf_item_id, movie_id):
        if self.request.get('exit'):
            self.redirect('/shelf/' + shelf_id + '/' + shelf_item_id)
        else:
            if self.request.get('movie_poster'):
                shelf_item_meta = ShelfItemMeta(shelf_item=ShelfItem.get(shelf_item_id), name='Movie Poster', type='image', value=self.request.get('movie_poster'))
            elif self.request.get('overview'):
                shelf_item_meta = ShelfItemMeta(shelf_item=ShelfItem.get(shelf_item_id), name='Movie Overview', type='text', value=self.request.get('overview'))
            elif self.request.get('tagline'):
                shelf_item_meta = ShelfItemMeta(shelf_item=ShelfItem.get(shelf_item_id), name='Tagline', type='text', value=self.request.get('tagline'))
            elif self.request.get('rating'):
                shelf_item_meta = ShelfItemMeta(shelf_item=ShelfItem.get(shelf_item_id), name='Movie Rating', type='text', value=self.request.get('rating'))
            #release_date
            elif self.request.get('release_date'):
                shelf_item_meta = ShelfItemMeta(shelf_item=ShelfItem.get(shelf_item_id), name='Release Date', type='text', value=self.request.get('release_date'))
            #run_time
            elif self.request.get('run_time'):
                shelf_item_meta = ShelfItemMeta(shelf_item=ShelfItem.get(shelf_item_id), name='Run Time', type='text', value=self.request.get('Run Time'))
            #trailer
            elif self.request.get('trailer'):
                shelf_item_meta = ShelfItemMeta(shelf_item=ShelfItem.get(shelf_item_id), name='Trailer', type='url', value=self.request.get('trailer'))
            #home_page
            elif self.request.get('home_page'):
                shelf_item_meta = ShelfItemMeta(shelf_item=ShelfItem.get(shelf_item_id), name='Home Page', type='url', value=self.request.get('home_page'))
            shelf_item_meta.put()
            self.redirect('/shelf/' + shelf_id + '/add/movie/meta/'+ shelf_item_id + '/' + movie_id)
    
    def get(self, shelf_id, shelf_item_id, movie_id):
        tmdbapi = TMDb('58bdd901955465b24e37631dd9f68ced')
        results = tmdbapi.getInfo(movie_id)
        values = {'results':results}
        self.response.out.write(template.render('templates/header.html', {}))
        self.response.out.write(template.render('templates/shelf/item/addmoviemeta.html', values))
        self.response.out.write(template.render('templates/footer.html', {}))
      
class ShelfDeletePage(webapp.RequestHandler):
    
    def post(self, shelf_id):
    
        if shelf_id != self.request.get('shelf_id'):
            self.redirect('/shelf/' + shelf_id)
        else:
            
            shelf = Shelf.get(shelf_id)
            
            # delete the shelf
            for item in shelf.items:
                for data in item.meta:
                    data.delete()
                item.delete()
            shelf.delete()
            
            # return to the shelf list page
            self.redirect('/shelf/list')
    
    def get(self, shelf_id):
        
        shelf=Shelf.get(shelf_id)
        if shelf.owner != users.get_current_user():
            self.redirect('/')
        values = {'shelf': Shelf.get(shelf_id)}
        
        self.response.out.write(template.render('templates/header.html', {}))
        self.response.out.write(template.render('templates/shelf/delete.html', values))
        self.response.out.write(template.render('templates/footer.html', {}))

class ShelfEditPage(webapp.RequestHandler):
    
    def post(self, shelf_id):
    
        shelf = Shelf.get(shelf_id)
        shelf.name = self.request.get('name')
        
        if self.request.get('public'):
            shelf.public = True;
        else:
            shelf.public = False;
            
        shelf.put()
        
        self.redirect('/shelf/list')
    
    def get(self, shelf_id):
        
        shelf=Shelf.get(shelf_id)
        if shelf.owner != users.get_current_user():
            self.redirect('/')
        values = {'shelf': Shelf.get(shelf_id),
                  'user': users.get_current_user()}
        
        self.response.out.write(template.render('templates/header.html', {}))
        self.response.out.write(template.render('templates/shelf/edit.html', values))
        self.response.out.write(template.render('templates/footer.html', {}))        
        